package com.example.liuxing.jdmall.controller;


import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.example.liuxing.jdmall.bean.RResult;
import com.example.liuxing.jdmall.constant.IdiyMessage;
import com.example.liuxing.jdmall.constant.NetworkConstant;
import com.example.liuxing.jdmall.db.UserDao;
import com.example.liuxing.jdmall.utils.NetWorkUtils;

import java.util.HashMap;

/**
 * Created by liuxing on 2017/7/13.
 */

public class LoginController extends BaseController {

    public LoginController(Context c) {
        super(c);
    }

    @Override
    protected void handleMessage(int action, Object... values) {
        switch (action) {
            case IdiyMessage.LOGIN_ACTION: { // 登录
                // 登录请求
                RResult result = login((String)values[0], (String)values[1]);
                modeChangeListener.onModelChanged(IdiyMessage.LOGIN_ACTION_RESULT, result);
            }
            case IdiyMessage.SAVE_USERTODB: { // 保存数据
                boolean result = saveUser2Db((String)values[0], (String)values[1]);
                modeChangeListener.onModelChanged(IdiyMessage.SAVE_USERTODB_RESULT, result);
            }
            case IdiyMessage.READ_USERTODB_ACTION: { // 读取user
                UserDao.UserInfo userInfo = acquireUser();
                modeChangeListener.onModelChanged(IdiyMessage.READ_USERTODB_ACTION_RESULT, userInfo);
            }
            case IdiyMessage.CLEAR_USER_ACTION: { // 读取user
                clearUser();
                modeChangeListener.onModelChanged(IdiyMessage.CLEAR_USER_ACTION_RESULT, 0);
            }
        }
    }

    private void clearUser() {
        UserDao userDao = new UserDao(context);
        userDao.clearUser();
    }

    private UserDao.UserInfo acquireUser() {
        UserDao userDao = new UserDao(context);
        return userDao.aquireUser();
    }

    public boolean saveUser2Db(String name, String pwd) {
        UserDao userDao = new UserDao(context);
        userDao.clearUser();
        return userDao.saveUser(name, pwd);
    }

    private RResult login(String username, String pwd) {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("username", username);
        params.put("pwd", pwd);
        String jsonString = NetWorkUtils.doPost(NetworkConstant.LOGIN_URL, params);
        //  处理json fastJson
        return JSON.parseObject(jsonString, RResult.class);
    }

}
